package routers

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/service/AdminService"
	"seawolf-admin-go/utility/response"
	"seawolf-admin-go/utility/token"
	"seawolf-admin-go/utility/tools"
	"strings"
)

// MiddlewareHandlerIsPermission 登录中间件
func MiddlewareHandlerIsPermission(r *ghttp.Request) {
	// 不需要权限的URL
	if tools.RegexpContains(tools.GetAdminNoPermissionUrl(), r.Request.URL.Path) {
		r.Middleware.Next()
		return
	}
	adminId := tools.GetAdminIdByRequest(r)
	if adminId < 1 {
		r.Response.ClearBuffer()
		r.Response.WriteJsonExit(response.JsonByAll(r, 10003, "请先登录"))
		return
	}
	ctx := r.GetCtx()
	isAdmin := false
	sessionData := token.GetSessionData(ctx, adminId)
	if sessionData != nil {
		isAdmin = gconv.Bool(sessionData["IsAdmin"])
	}
	// 获取到URL转权限
	perms := strings.Replace(strings.Trim(r.Request.URL.Path, "/"), "/", ":", -1)

	if checkPermsByAdminId(ctx, perms, adminId, isAdmin) {
		r.Middleware.Next()
		return
	} else {
		r.Response.ClearBuffer()
		r.Response.WriteJsonExit(response.JsonByAll(r, 10004, "没有操作权限"))
		return
	}
}

func checkPermsByAdminId(ctx context.Context, perms string, adminId int64, isAdmin bool) bool {
	// 如果是超级管理员，直接通过
	if isAdmin {
		return true
	}
	peramArr, err := AdminService.GetPermsByAdminId(ctx, adminId)
	if err != nil {
		return false
	}

	//fmt.Println("perms ", perms)
	//fmt.Println("peramArr ", peramArr)

	for _, item := range peramArr {
		if item == perms {
			fmt.Println("item == perms ", item == perms)
			return true
		}
	}

	return false
}
